import { watch } from 'vue';
import { theme as antdTheme } from 'ant-design-vue';
import { themeColor } from '@/layouts/Header/com/constant';

const colorMap = {
  colorPrimary: '#1677ff',
};

const defaultSettings = {
  ...colorMap,
  themeMode: 'realDark',
  layout: 'horizontal', //vertical、horizontal
  collapsed: true,
  inline: false,
};

const settingKey = 'layoutSetting';

export const useThemeStore = defineStore('theme', () => {
  const layoutSetting = reactive({ ...defaultSettings });

  const themeConfig = reactive({
    algorithm:
      themeColor[layoutSetting.themeMode] || antdTheme.defaultAlgorithm,
    token: {
      colorPrimary: layoutSetting.colorPrimary,
    },
  });

  watch(
    [() => layoutSetting.themeMode, () => layoutSetting.colorPrimary],
    (state) => {
      const [themeMode, colorPrimary] = state;
      toggleTheme(themeMode);
      setColorPrimary(colorPrimary);
    },
  );

  watch(
    () => layoutSetting,
    (newVal) => {
      localStorage.setItem(settingKey, JSON.stringify(newVal));
    },
    { deep: true },
  );

  // 切换主题
  const toggleTheme = (themeName) => {
    const root = document.documentElement;
    if (themeName === 'realDark' || themeName === 'dark') {
      root.setAttribute('data-theme', 'dark');
    } else {
      root.removeAttribute('data-theme');
    }
    themeConfig.algorithm = themeColor[themeName];
  };
  // 设置主题色
  const setColorPrimary = (color) => {
    themeConfig.token.colorPrimary = color;
    const root = document.documentElement;
    root.style.setProperty('--color-primary', color);
  };

  const initColor = () => {
    const root = document.documentElement;
    Object.keys(colorMap).forEach((key) => {
      // 将小驼峰转为短横线
      const keyName = key.replace(/([A-Z])/g, '-$1').toLowerCase();
      root.style.setProperty(`--${keyName}`, layoutSetting[key]);
    });
  };

  const updateLayoutSetting = (setting) => {
    Object.assign(layoutSetting, setting);
  };

  const initLayoutSetting = () => {
    const cacheSetting = localStorage.getItem(settingKey);
    if (cacheSetting) {
      Object.assign(layoutSetting, JSON.parse(cacheSetting));
    }
    toggleTheme(layoutSetting.themeMode);
    initColor();
  };

  return {
    themeConfig,
    layoutSetting,
    toggleTheme,
    updateLayoutSetting,
    initLayoutSetting,
  };
});
